<?php
class ControllerSaleMainPurchaseOrder extends Controller {
  private $error = array();

  public function vendor(){
    $this->load->model('sale/purchase_order');
    $json = array();
    $filter_name = I('get.filter_name');
    if(!$filter_name){
      $filter_name='';
    }
    $vendors = $this->model_sale_purchase_order->getVendors($filter_name);
    if($vendors){
      $json = $vendors;
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }

  public function product(){
    $json = array();

    if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_model'])) {
      $this->load->model('catalog/product');
      $this->load->model('catalog/option');
      $this->load->model('sale/purchase_order');

      

      if (isset($this->request->get['filter_name'])) {
        $filter['pd.name'] = array('like', '%'.$this->request->get['filter_name'].'%');
      }
      if(isset($this->request->get['filter_vendor'])){
        $filter['vendor.vendor'] = $this->request->get['filter_vendor'];
      }
      $results = $this->model_sale_purchase_order->getProducts($filter);

      foreach ($results as $result) {
        $option_data = array();

        $product_options = $this->model_catalog_product->getProductOptions($result['product_id']);

        foreach ($product_options as $product_option) {
          $option_info = $this->model_catalog_option->getOption($product_option['option_id']);

          if ($option_info) {
            $product_option_value_data = array();

            foreach ($product_option['product_option_value'] as $product_option_value) {
              $option_value_info = $this->model_catalog_option->getOptionValue($product_option_value['option_value_id']);

              if ($option_value_info) {
                $product_option_value_data[] = array(
                  'product_option_value_id' => $product_option_value['product_option_value_id'],
                  'option_value_id'         => $product_option_value['option_value_id'],
                  'name'                    => $option_value_info['name'],
                  'price'                   => (float)$product_option_value['price'], 
                  'price_prefix'            => $product_option_value['price_prefix']
                );
              }
            }

            $option_data[] = array(
              'product_option_id'    => $product_option['product_option_id'],
              'product_option_value' => $product_option_value_data,
              'option_id'            => $product_option['option_id'],
              'name'                 => $option_info['name'],
              'type'                 => $option_info['type'],
              'value'                => $product_option['value'],
              'required'             => $product_option['required']
            );
          }
        }

        $json[] = array(
          'product_id' => $result['product_id'],
          'name'       => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
          'model'      => $result['model'],
          'cost'          => $result['product_cost'],
          'sku'         =>$result['sku'],
          'option'     => $option_data,
          'price'      => $result['price']
        );
      }
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }
  public function exportShipping(){
    $po_id = I('get.po_id');
    if(!$po_id){
      $po_id = 0;
    }
    $this->load->model('sale/purchase_order');
    $po = $this->model_sale_purchase_order->getPo($po_id);

    $data['po'] = $po;
    //var_dump($po);die();
    if(!$po){
      $this->load->language('error/not_found');
 
      $this->document->setTitle($this->language->get('heading_title'));

      $data['heading_title'] = $this->language->get('heading_title');
 
      $data['text_not_found'] = $this->language->get('text_not_found');
 
      $data['breadcrumbs'] = array();

      $data['breadcrumbs'][] = array(
        'text' => $this->language->get('heading_title'),
        'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
      );
 

      $data['footer'] = $this->load->controller('common/footer');
 
      $this->response->setOutput($this->load->view('error/not_found.tpl', $data));
    }
    $po_products = $this->model_sale_purchase_order->getPoProducts($po_id);
    $count = 0;
    foreach ($po_products as $key => $po_product) {
      $count += $po_product['qty'];
    }

    $this->load->library('PHPExcel/PHPExcel');
    $objReader = PHPExcel_IOFactory::createReader('Excel5');
    $objPHPExcel = $objReader->load(DIR_SYSTEM . "template/order_shipping.xls"); 
    $objPHPExcel->getProperties()->setCreator("Think-tec")
               ->setLastModifiedBy("Think-tec")
               ->setTitle("Bai Huo Zhan PO")
               ->setSubject("Bai Huo Zhan PO")
               ->setDescription("Bai Huo Zhan PO")
               ->setKeywords("Bai Huo Zhan, Think-tec")
               ->setCategory("Think-tec");
    // $objPHPExcel->setActiveSheetIndex(0);
    $objActSheet = $objPHPExcel->getActiveSheet();
    $objPHPExcel->getActiveSheet()->getStyle('C1')->getFont()->setSize(48);
    $objActSheet->setCellValue('C1', $po['logcenter_info']['shipping_zone_city']);
    //$objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->setSize(16);
    $objActSheet->setCellValue('B2', $po['included_order_ids']);
    $objPHPExcel->getActiveSheet()->getStyle('B3')->getFont()->setSize(16);
    $objActSheet->setCellValue('B3', $po['id']);
    $objPHPExcel->getActiveSheet()->getStyle('B5')->getFont()->setSize(16);
    $objActSheet->setCellValue('B5', $po['logcenter_info']['firstname']);
    $objActSheet->setCellValue('B6', $po['logcenter_info']['address_1']);
    $objActSheet->setCellValue('B7', $po['logcenter_info']['telephone']);

    //$objPHPExcel->getActiveSheet()->getStyle('A7:G'.$row_num)->getFont()->setSize(12);
    
    $objActSheet->setTitle('采购单');


    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    ob_end_clean();
    // Redirect output to a client’s web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="PO_BHZ_'.date('Y-m-d-H-i',time()).'.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objWriter->save('php://output'); 
    exit;
  }
  public function export(){
    $po_id = I('get.po_id');
    if(!$po_id){
      $po_id = 0;
    }
    $this->load->model('sale/purchase_order');
    $po = $this->model_sale_purchase_order->getPo($po_id);
    $data['po'] = $po;
    if(!$po){
      $this->load->language('error/not_found');
 
      $this->document->setTitle($this->language->get('heading_title'));

      $data['heading_title'] = $this->language->get('heading_title');
 
      $data['text_not_found'] = $this->language->get('text_not_found');
 
      $data['breadcrumbs'] = array();

      $data['breadcrumbs'][] = array(
        'text' => $this->language->get('heading_title'),
        'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
      );
 

      $data['footer'] = $this->load->controller('common/footer');
 
      $this->response->setOutput($this->load->view('error/not_found.tpl', $data));
    }
    $po_products = $this->model_sale_purchase_order->getPoProducts($po_id);
    $data['po_products'] = $po_products;

    $this->load->library('PHPExcel/PHPExcel');
    $objReader = PHPExcel_IOFactory::createReader('Excel5');
    $objPHPExcel = $objReader->load(DIR_SYSTEM . "template/po_tpl.xls"); 
    $objPHPExcel->getProperties()->setCreator("Think-tec")
               ->setLastModifiedBy("Think-tec")
               ->setTitle("Bai Huo Zhan PO")
               ->setSubject("Bai Huo Zhan PO")
               ->setDescription("Bai Huo Zhan PO")
               ->setKeywords("Bai Huo Zhan, Think-tec")
               ->setCategory("Think-tec");
    // $objPHPExcel->setActiveSheetIndex(0);
    $objActSheet = $objPHPExcel->getActiveSheet();
    $objActSheet->setCellValue('B2', $po['id']);
    $objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objActSheet->setCellValue('F2', date('Y-m-d H:i',time()));
    $objActSheet->setCellValue('B3', $po['vendor_id']);
    $objActSheet->setCellValue('B4', $po['vendor']['vendor_name']);
    $objActSheet->setCellValue('F3', $po['vendor']['firstname']);
    $objActSheet->setCellValue('F4', $po['vendor']['telephone']);

    $row_num = 6;
    $styleBorderOutline = array(
      'borders' => array(
        'outline' => array(
          'style' => PHPExcel_Style_Border::BORDER_THIN,
        ),
      ),
    );
    $objPHPExcel->getActiveSheet()->insertNewRowBefore(7, count($po_products));
    $count = 0;
    foreach ($po_products as $key => $po_product) {
      $row_num++;
      $objActSheet->setCellValue('A'.$row_num, $row_num-6);
      $objActSheet->setCellValue('B'.$row_num, $po_product['name'].' '.$po_product['option_name']);
      $objActSheet->setCellValue('C'.$row_num, $po_product['sku']);
      $objActSheet->setCellValue('D'.$row_num, $po_product['qty']);
      $objActSheet->setCellValue('E'.$row_num, $po_product['unit_price']);
      $objActSheet->setCellValue('F'.$row_num, $po_product['price']);
      $objActSheet->setCellValue('G'.$row_num, $po_product['comment']);

      $count += $po_product['qty'];

      $objPHPExcel->getActiveSheet()->getStyle('A'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('B'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('C'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('D'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('E'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('F'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('G'.$row_num)->applyFromArray($styleBorderOutline);
    }
    $row_num++;

    $objActSheet->setCellValue('D'.$row_num, $count);
    $objActSheet->setCellValue('F'.$row_num, $po['total']);
    $row_num++;
    $objActSheet->setCellValue('F'.$row_num, date('Y-m-d', strtotime($po['deliver_time'])));

    $objPHPExcel->getActiveSheet()->getStyle('A7:G'.$row_num)->getFont()->setSize(16);
    
    $objActSheet->setTitle('采购单');


    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    ob_end_clean();
    // Redirect output to a client’s web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="PO_BHZ_'.date('Y-m-d-H-i',time()).'.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objWriter->save('php://output'); 
    exit;
  }

  public function index() {

    $this->document->setTitle('采购单');

    $this->load->model('sale/purchase_order');

    $this->getList();
  }

  public function add() {
    $this->document->setTitle('新增采购单');
    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/bhz_ctl.js');

    $this->load->model('sale/purchase_order');

    $this->form();
  }

  public function edit(){

    $this->document->setTitle('查看采购单');

    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/bhz_ctl.js');

    $this->load->model('sale/purchase_order');
    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '采购单',
      'href' => $this->url->link('sale/purchase_order', 'token=' . $this->session->data['token'] , 'SSL')
    );

    $data['token'] = $this->session->data['token'];

    $id = I('get.po_id');
    if(!$id){
      $id=0;
    }
    
    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }
    
    $po = $this->model_sale_purchase_order->getPo($id);
    $data['po'] = $po;
    $po_products = $this->model_sale_purchase_order->getPoProducts($id);
    $data['po_products'] = $po_products;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/purchase_order_edit.tpl', $data));
  }


  public function view(){

    $this->document->setTitle('查看采购单');

    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/bhz_ctl.js');

    $this->load->model('sale/purchase_order');
    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '采购单',
      'href' => $this->url->link('sale/purchase_order', 'token=' . $this->session->data['token'] , 'SSL')
    );

    $data['token'] = $this->session->data['token'];

    $id = I('get.po_id');
    if(!$id){
      $id=0;
    }
    

    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }
    
    $po = $this->model_sale_purchase_order->getPo($id);
    $data['po'] = $po;
    $po_products = $this->model_sale_purchase_order->getPoProducts($id);
    $data['po_products'] = $po_products;
    $po_histories = $this->model_sale_purchase_order->getPoHistory($id);
    $data['po_histories'] = $po_histories;
    $data['included_orders'] = explode(',', $po['included_order_ids']);

    if($po['status']==3) {
      $data['forceCompleteBtn'] = '审核完成采购单';
    }

    if($po['status']==7) {
      $data['need_allow'] = true;
    }

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/main_purchase_order_view.tpl', $data));
  }

  public function save(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/purchase_order');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
      if(!$data['deliver_time'] || !$data['products']||!$data['vendor']){
        $this->response->setOutput(json_encode(array('success'=>false, 'info'=>'数据不完整')));
      }
      else{
        $po_id = $this->model_sale_purchase_order->addPo($data, $this->user->getId());
      }
      $this->response->setOutput(json_encode(array('success'=>true, 'info'=>$po_id)));
      return;
    }
  }

  public function saveStock(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/purchase_order');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
      
      if(!$data['products']){
        $this->response->setOutput(json_encode(array('error'=>'数据不完整')));
        return;
      }

      $to_save_stock = array();
      foreach ($data['products'] as $po_product) {
        $to_save_stock[$po_product['po_product_id']] = $po_product['stock'];
      }
      $to_save_stock2 = array();
      // $id = I('post.po_id');
      $id = $data['po_id'];
      if(!$id){
        $id=0;
      }
      $po = $this->model_sale_purchase_order->getPo($id);
      //判断po状态，如果是已经结算或者已经关闭，则不允许修改po数量
      if($po['status'] == 5 || $po['status'] == 9) {
        $this->response->setOutput(json_encode(array('error'=>'不能修改已结算和已关闭采购单')));
        return;
      }

      $po_products = $this->model_sale_purchase_order->getPoProducts($id);
      //检查stock数量是否在-delivered_qty之间~qty-delivered_qty之间
      $stock_error = array();
      foreach ($po_products as $po_p) {
        if(isset($to_save_stock[$po_p['id']])) {
          if($to_save_stock[$po_p['id']] > $po_p['qty']-$po_p['delivered_qty'] || $to_save_stock[$po_p['id']] < -$po_p['delivered_qty']) {
            $stock_error[$po_p['id']] = '数值需要为0' . '~' . ($po_p['qty']-$po_p['delivered_qty']) . '之间';
          }
          $to_save_stock2[$po_p['id']] = $to_save_stock[$po_p['id']];
        }
      }
      if(!empty($stock_error)) {
        $this->response->setOutput(json_encode(array('error'=>'入库数量不对', 'data'=>$stock_error)));
        return;
      }
      
      $this->model_sale_purchase_order->setStock($id, $to_save_stock2);
      $event_data['po_id'] = $id;
      $event_data['to_save_stock'] = $to_save_stock;

      $this->event->trigger('po.product.addstock', $event_data);

      //添加po入库操作记录
      $this->model_sale_purchase_order->addStock($id, $to_save_stock2);  
        

      //判断库存是否全部匹配，如果是的话，就置为全部收货，否则置为部分收货
      $po_products = $this->model_sale_purchase_order->getPoProducts($id);
      $delivered_qty_total = 0;
      $fully_delivered = true;
      $po_status = 0;
      foreach ($po_products as $po_p) {
        $delivered_qty_total += $po_p['delivered_qty'];
        if($po_p['qty'] != $po_p['delivered_qty']) {
          $fully_delivered = false;
        }
      }
      if($fully_delivered) {
        $po_status = 4;
      } elseif($delivered_qty_total!=0) {
        $po_status = 3;
      }
      if($po_status != 0) {
        $this->model_sale_purchase_order->changePoStatus($id, $po_status);
        //全部入库记录更新
        if($po_status == 4) {
          $this->load->model('catalog/logcenter');
          $logcenter_info = $this->model_catalog_logcenter->getLogcenterByUserId($this->user->getId());
          $comment = '采购单商品已全部收到';
          $this->model_sale_purchase_order->addPoHistory($id, $this->user->getId(), $logcenter_info['logcenter_name'], $comment);    
        }

        //强制置为入库记录为待审核
        $this->model_sale_purchase_order->changePoStatus($id, 7);
        
      }

      $this->response->setOutput(json_encode(array('success'=>'修改库存成功')));
      return;
    } 
  }


  public function allowStock(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/purchase_order');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);

      // $id = I('post.po_id');
      $id = $data['po_id'];
      if(!$id){
        $id=0;
      }
      $po = $this->model_sale_purchase_order->getPo($id);
      //判断po状态，如果是已经结算或者已经关闭，则不允许修改po数量
      if($po['status'] == 5 || $po['status'] == 9) {
        $this->response->setOutput(json_encode(array('error'=>'不能修改已结算和已关闭采购单')));
        return;
      }  

      //判断库存是否全部匹配，如果是的话，就置为全部收货，否则置为部分收货
      $po_products = $this->model_sale_purchase_order->getPoProducts($id);
      $delivered_qty_total = 0;
      $fully_delivered = true;
      $po_status = 0;
      foreach ($po_products as $po_p) {
        $delivered_qty_total += $po_p['delivered_qty'];
        if($po_p['qty'] != $po_p['delivered_qty']) {
          $fully_delivered = false;
        }
      }
      if($fully_delivered) {
        $po_status = 4;
      } elseif($delivered_qty_total!=0) {
        $po_status = 3;
      }
      if($po_status != 0) {
        $this->model_sale_purchase_order->changePoStatus($id, $po_status);
        //入库批准
        if(1) {
          $this->load->model('catalog/logcenter');
          $comment = '批准入库记录';
          $this->model_sale_purchase_order->addPoHistory($id, $this->user->getId(), $this->user->getUserName(), $comment);  
        }
      }

      $this->response->setOutput(json_encode(array('success'=>'成功批准入库记录')));
      return;
    } 
  }

  public function delete() {
    $json = array();

    $this->load->model('sale/purchase_order');

    $id = I('get.po_id');
    if(!$id){
      $id=0;
    }
    
    $po = $this->model_sale_purchase_order->getPo($id);
    if(!$po||$po['status']!=0) {
      $json['error'] = '非新增状态采购单不能删除';
    }
    else {
      $this->model_sale_purchase_order->deletePo($id);
      $json['success'] = '删除成功';
    }

    if (isset($this->request->server['HTTP_ORIGIN'])) {
      $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
      $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
      $this->response->addHeader('Access-Control-Max-Age: 1000');
      $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }

  protected function form(){
        $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '采购单',
      'href' => $this->url->link('sale/purchase_order', 'token=' . $this->session->data['token'] , 'SSL')
    );

    $data['token'] = $this->session->data['token'];

    $id = I('get.po_id');
    if(!$id){
      $id=0;
    }
    

    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }
    
    $po = $this->model_sale_purchase_order->getPo($id);
    $data['po'] = $po;
    $po_products = $this->model_sale_purchase_order->getPoProducts($id);
    $data['po_products'] = $po_products;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/purchase_order.tpl', $data));
  }

  

  protected function getList() {
    $page = I('get.page');
    if(!$page){
      $page = 1;
    }
    if($this->user->getLp()){
      $filter['po.user_id'] = $this->user->getId();
    }
    else if($this->user->getVp()){
      $filter['po.vendor_id'] = $this->user->getId();
    }
    else{
      
    }
    $data = I('get.');

/*
    if(!empty($data['filter_date_start'])){
      $filter_date_start = $data['filter_date_start'];
    }else{
      $filter_date_start = '';
    }

    if(!empty($data['filter_date_end'])){
      $filter_date_end = $data['filter_date_end'];
    }else{
      $filter_date_end = '';
    }

    $filter['po.date_added'] = array('between',array($filter_date_start,$filter_date_end));
*/
    /*
     * 修正分页后时间下拉框不能操作的异常
     * @author sonicsjh
     */
    if (!empty($data['filter_date_start']) && !empty($data['filter_date_end'])) {
        $filter_date_start = $data['filter_date_start'];
        $filter_date_end = $data['filter_date_end'];
        $filter['po.date_added'] = array('between', array($filter_date_start.' 00:00:00',$filter_date_end.' 23:59:59'));
    }else if (!empty($data['filter_date_start'])) {
        $filter_date_start = $data['filter_date_start'];
        $filter['po.date_added'] = array('gt', $data['filter_date_start'].' 00:00:00');
    }else if (!empty($data['filter_date_end'])) {
        $filter_date_end = $data['filter_date_end'];
        $filter['po.date_added'] = array('lt', $data['filter_date_end'].' 23:59:59');
    }

    if(!empty($data['filter_vendor_name'])){
      $filter_vendor_name = trim($data['filter_vendor_name']);
      $filter['v.vendor_name'] = array('like',"%".$filter_vendor_name."%");
    }

    if(!empty($data['filter_logcenter'])){
      $filter_logcenter = trim($data['filter_logcenter']);
      $filter['lg.logcenter_name'] = array('like',"%".$filter_logcenter."%");
    }

    if(!empty($data['filter_sku'])){
      $filter_sku = trim($data['filter_sku']);
      $pos_id_array = $this->model_sale_purchase_order->getPoIdsBySku($filter_sku);
      if(!$pos_id_array){
        $pos_id_array = array('0');
      }
      $filter['po.id'] = array('in',$pos_id_array);
    }

    if(isset($data['filter_status'])){
      $filter_status = trim($data['filter_status']);
      if($filter_status!='*'){
        $filter['po.status'] = $filter_status;
      }  
    }else{
      $data['filter_status'] = '*';
    }

    $po_list =  $this->model_sale_purchase_order->getList($page, $filter);
    $order_total = $this->model_sale_purchase_order->getListCount($filter);

    foreach ($po_list as $key => $value) {
      $po_list[$key]['all_color'] = $this->model_sale_purchase_order->checkPoOrderDate($value['date_added'],$value['status']);
    }
    $data['status_array'] = getPoStatus();
    $data['status_array']['*'] = '全部';
    $pagination = new Pagination();
    $pagination->total = $order_total;
    $pagination->page = $page;
    $pagination->limit = $this->config->get('config_limit_admin');
    $pagination->url = $this->url->link('sale/main_purchase_order', 'token=' . $this->session->data['token'] . '&page={page}'.'&filter_date_end='.$filter_date_end.'&filter_date_start='.$filter_date_start.'&filter_logcenter='.$filter_logcenter.'&filter_status='.$data['filter_status'].'&filter_vendor_name='.$data['filter_vendor_name'].'&filter_sku='.$data['filter_sku'], 'SSL');

    $data['pagination'] = $pagination->render();

    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '采购单',
      'href' => $this->url->link('sale/main_purchase_order', 'token=' . $this->session->data['token'] , 'SSL')
    );

    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }

    $data['token'] = $this->session->data['token'];
    
    $data['po_list'] = $po_list;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/main_purchase_order_list.tpl', $data));
  }

  function validateDate($date, $format = 'Y-m-d H:i:s')
  {
      $d = DateTime::createFromFormat($format, $date);
      return $d && $d->format($format) == $date;
  }

  public function genVendorBill(){
    $vendor_bill_month = I('get.year_month');
    $month_valid = $this->validateDate($vendor_bill_month, 'Y-m');
    if(!$month_valid) {
      $this->session->data['error'] = '请选择有效的年月日期';
      $this->response->redirect($this->url->link('sale/order', 'token=' . $this->session->data['token'], 'SSL'));
    }
    //获取选择月份之前半年内所有还未对账的完成状态的订单
    $d = DateTime::createFromFormat('Y-m', $vendor_bill_month);
    $cur_year_month = $d->format('Y-m-01');
    $cur_month = $d->format('Y-m-21');
    /*
     * 20170925修改后还原，仅用于生成8.21-9.20的供应商对账单，错开猛龙11w的大额采购单
     * @author sonicsjh 
     */
    //$cur_month = $d->format('Y-m-20 14:00:00');
    $d->modify('-12 month');
    $end_month = $d->format('Y-m-d');
    $this->load->model('sale/vendor_bill');
    $this->load->model('sale/purchase_order');
    $billed_po = $this->model_sale_vendor_bill->getBilledPo($cur_month, $end_month);
    $billed_po_ids = array();
    foreach ($billed_po as $bo) {
      $billed_po_ids[] = $bo['po_id'];
    }

    $vendor_ids = $this->model_sale_purchase_order->getVendorIdsFromPo($cur_month, $end_month, $billed_po_ids);

    foreach ($vendor_ids as $vendor_id) {
      $bill_data = $this->model_sale_purchase_order->getToBillPo($cur_month, $end_month, $billed_po_ids, $vendor_id['vendor_id']);  
      $bill_data_full[$vendor_id['vendor_id']] = $bill_data;
    }
    // die();
    $commission = 1;
    foreach ($bill_data_full as $vendor_id=>$bill_data) {
      $po_total = 0;
      $po_ids = array();
      foreach ($bill_data as $po) {
        $po_total += (float)$po['total'];
        $po_ids[] = $po['id'];
      }
      $commission_total = $po_total*$commission;
      $data = array();

      //此处的$vendor_id是po表中的vendor_id 对应的是 vendors表中的user_id
      $this->load->model('catalog/vendor');
      $vendor_info = $this->model_catalog_vendor->getVendorByUserId($vendor_id);
      $data['vendor_id'] = $vendor_info['vendor_id'];
      $data['year_month'] = $cur_year_month;
      $data['total'] = $commission_total;
      $data['po_total'] = $po_total;
      $data['date_added'] = date('Y-m-d H:i:s', time());
      $vendor_bill_id = $this->model_sale_vendor_bill->saveVendorBill($data, $po_ids);

      //添加生成po操作记录
      $this->load->model('user/user');
      $user_info = $this->model_user_user->getUser($this->user->getId());
      $comment = '新增品牌商对账单';
      $this->model_sale_vendor_bill->addVendorBillHistory($vendor_bill_id, $this->user->getId(), $user_info['fullname'], $comment);      
    }
    
    // var_dump($bill_data_full);die();

    $this->session->data['success'] = '生成品牌厂商对账单成功';
    $this->response->redirect($this->url->link('sale/vendor_bill', 'token=' . $this->session->data['token'], 'SSL'));
  }

  public function forceCompletePo() {
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/purchase_order');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
      // $id = I('post.po_id');
      $id = $data['po_id'];
      if(!$id){
        $id=0;
      }
      $po = $this->model_sale_purchase_order->getPo($id);
      //判断po状态
      if($po['status'] != 3) {
        $this->response->setOutput(json_encode(array('error'=>'只能审核完成部分收货状态采购单')));
        return;
      }

      if($po['status'] == 3) {
        //修改po单的total
        $po_products = $this->model_sale_purchase_order->getPoProducts($id);
        $new_total = 0;
        foreach ($po_products as $po_product) {
          $new_total += (float)$po_product['unit_price']*(float)$po_product['delivered_qty'];
        }
        $this->model_sale_purchase_order->setPoTotal($id, $new_total);

        //修改po的status到审核完成
        $po_status = 6;
        $this->model_sale_purchase_order->changePoStatus($id, $po_status);

        //添加po状态修改操作记录
        $this->load->model('user/user');
        $user_info = $this->model_user_user->getUser($this->user->getId());
        $comment = '审核完成采购单。采购单金额改为：' . $new_total . '￥';
        $this->model_sale_purchase_order->addPoHistory($id, $this->user->getId(), $user_info['fullname'], $comment);  
      }

      $this->response->setOutput(json_encode(array('success'=>'修改采购单状态成功')));
      return;
    } 
  }
  public function exportLists(){
    $this->load->model('sale/purchase_order');
    if($this->user->getLp()){
      $filter['po.user_id'] = $this->user->getId();
    }
    else if($this->user->getVp()){
      $filter['po.vendor_id'] = $this->user->getId();
    }

    $data = I('get.');

    if(isset($data['filter_date_start'])){
      $filter_date_start = $data['filter_date_start'];
    }else{
      $filter_date_start = '0000-00-00';
    }

    if(isset($data['filter_date_end'])){
      $filter_date_end = $data['filter_date_end'].' 23:59:59';
    }else{
      $filter_date_end = '9999-12-31';
    }

    $filter['po.date_added'] = array('between',array($filter_date_start,$filter_date_end));
    $filter2 = $filter;
    if(isset($data['filter_vendor_name'])){
      $filter_vendor_name = trim($data['filter_vendor_name']);
      $filter['v.vendor_name'] = array('like',"%".$filter_vendor_name."%");
    }

    if(isset($data['filter_logcenter'])){
      $filter_logcenter = trim($data['filter_logcenter']);
      $filter['lg.logcenter_name'] = array('like',"%".$filter_logcenter."%");
    }

    if(isset($data['filter_status'])){
      $filter_status = trim($data['filter_status']);
      if($filter_status!='*'){
        $filter['po.status'] = $filter_status;
      }  
    }

    if(!empty($data['filter_sku'])){
      $filter_sku = trim($data['filter_sku']);
      $pos_id_array = $this->model_sale_purchase_order->getPoIdsBySku($filter_sku);
      if(!$pos_id_array){
        $pos_id_array = array('0');
      }
      $filter['po.id'] = array('in',$pos_id_array);
    }

    $po_list =  $this->model_sale_purchase_order->getAllProductList($filter);

    $status_array = getPoStatus();
    foreach ($po_list as $key => $value) {
      $save_data[] = array(
        'name'          =>  $value['name'],
        'option_name'   =>  $value['option_name'],
        'qty'           =>  $value['qty'],
        'price'         =>  $value['price'],
        'unit_price'    =>  $value['unit_price'],
        'delivered_qty' =>  $value['delivered_qty'],
        'packing_no'    =>  $value['packing_no'],
        'id'            =>  $value['id'],
        'date_added'    =>  $value['date_added'],
        'total'         =>  $value['total'],
        'vendor_name'   =>  $value['vendor_name'],
        'logcenter_name'=>  $value['logcenter_name'],
        'count'         =>  $value['count'],
        'status'        =>  $status_array[$value['status']],
        'sku'           =>  $value['sku'],
        );
    }
      // var_dump($save_data);die();
    $this->load->library('PHPExcel/PHPExcel');
    $objPHPExcel = new PHPExcel();    
    $objProps = $objPHPExcel->getProperties();    
    $objProps->setCreator("Think-tec");
    $objProps->setLastModifiedBy("Think-tec");    
    $objProps->setTitle("Think-tec Contact");    
    $objProps->setSubject("Think-tec Contact Data");    
    $objProps->setDescription("Think-tec Contact Data");    
    $objProps->setKeywords("Think-tec Contact");    
    $objProps->setCategory("Think-tec");
    $objPHPExcel->setActiveSheetIndex(0);     
    $objActSheet = $objPHPExcel->getActiveSheet(); 
       
    $objActSheet->setTitle('Sheet1');
    $col_idx = 'A';
    $headers = array( '编号','商品名称','选项', '单价','数量','总价','箱入数','已收货数量', '创建时间',   '采购金额',  '供应商', '物流中心',     '商品品种', '采购单状态','条形码');
    $row_keys = array('id','name','option_name','unit_price','qty','price','packing_no','delivered_qty',   'date_added', 'total','vendor_name','logcenter_name',  'count', 'status','sku');
    foreach ($headers as $header) {
      $objActSheet->setCellValue($col_idx++.'1', $header);  
    }
    //添加物流信息
    $i = 2;
    foreach ($save_data as $rlst) {
      $col_idx = 'A';
      foreach ($row_keys as $rk) {
        // $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]); 
        $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
      }
      $i++;
    } 

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    
    ob_end_clean();
    // Redirect output to a client’s web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="main_purchase_order_'.date('Y-m-d',time()).'.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');

    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objWriter->save('php://output'); 
    exit;
  }
  public function test(){
      $this->load->model('sale/purchase_order');
      if($this->user->getLp()){
        $userid = $this->user->getId();
      }
      $this->model_sale_purchase_order->test($userid);
  }
}